const state = () => {
  return {
    // 购物车的数组，用来存储购物车中每个商品的信息对象
    // 每个商品的信息对象，都包含如下 6 个属性：
    // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
    cart: JSON.parse(uni.getStorageSync('cart') || '[]')
  }
}

const mutations = {
  addToCart(state, payload) {
    const result = state.cart.find(x => x.goods_id === payload.goods_id)
    if (!result) {
      state.cart.push(payload)
    } else {
      result.goods_count++
    }
    this.commit('cart/saveStorage')
  },

  // 进行本地保存
  saveStorage(state) {
    uni.setStorageSync('cart', JSON.stringify(state.cart))
  },

  // 更新商品状态
  updateGoodsState(state, payload) {
    const result = state.cart.find(x => x.goods_id === payload.goods_id)
    if (result) {
      result.goods_state = payload.goods_state
      this.commit('cart/saveStorage')
    }
  },

  // 更新商品数量
  updateGoodsCount(state, payload) {
    const result = state.cart.find(x => x.goods_id === payload.goods_id)
    if (result) {
      result.goods_count = payload.goods_count
      this.commit('cart/saveStorage')
    }
  },

  // 删除某一个商品
  removeGoodsById(state, payload) {
    // 将id不相同的返回，形成一个新数组，赋值给cart
    state.cart = state.cart.filter(x => x.goods_id !== payload.goods_id)
    this.commit('cart/saveStorage')
  },

  // 全选、反选
  updateAll(state, payload) {
    state.cart.forEach(x => x.goods_state = payload)
    this.commit('cart/saveStorage')
  }
}

const actions = {}

const getters = {

  // 购物车中商品的总数量
  total(state) {
    return state.cart.reduce((sum, item) => sum += item.goods_count, 0)
  },

  // 购物车中勾选商品的数量
  checkedCount(state) {
    return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count, 0)
  },

  // 勾选商品的总价
  checkedGoodsAmount(state) {
    return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count * item.goods_price,
      0).toFixed(2)
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  getters,
  actions
}
